/*
 * @Author: yangni 920556271@qq.com
 * @Date: 2024-03-27 15:57:33
 * @LastEditors: yangni 920556271@qq.com
 * @LastEditTime: 2024-04-21 18:52:03
 * @FilePath: /yt-devops/lib/pages/devices/device_tab/basic_info/setting/setting_form/setting_form_widget.dart
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import 'dart:async';
import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:collection/collection.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:native_dart_package/native_dart_package.dart';
import 'package:reactive_forms/reactive_forms.dart';
import 'package:sprintf/sprintf.dart';
import 'package:yt_devops/components/gaps.dart';
import 'package:yt_devops/components/yt_form/widgets/form_text_field.dart';
import 'package:yt_devops/components/yt_form/widgets/reactive_text_select.dart';
import 'package:yt_devops/pages/devices/device_list/device_list_model.dart';
import 'package:yt_devops/pages/devices/device_tab/basic_info/setting/setting_form/setting_form_model.dart';
import 'package:yt_devops/pages/devices/device_tab/components/fix_title_width_input.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/utils/brn_row1_delegate.dart';

class SettingFormWidget extends StatefulWidget {
  final List<SettingFormModel> model;
  final Map<String, dynamic> formData;
  Map<String, dynamic> data;

  SettingFormWidget(
      {super.key, this.model = const [], this.formData = const {}})
      : data = jsonDecode(jsonEncode(formData));

  @override
  State<SettingFormWidget> createState() => SettingFormWidgetState();
}

class SettingFormWidgetState extends State<SettingFormWidget> {
  List<Widget> formItems = [];

  FormGroup Function() buildForm = () => fb.group(<String, Object>{});

  TextStyle valueStyle =
      TextStyles.styleWith(14.sp, color: Colour.mainTextColor);

  InputDecoration decoration = InputDecoration(
    contentPadding: EdgeInsets.zero,
    hintStyle: TextStyles.lf14,
    enabledBorder: const OutlineInputBorder(
      borderSide: BorderSide(color: Colour.dividerColor),
    ),
  );

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Form(
        child: ListView.separated(
      shrinkWrap: true,
      itemBuilder: (context, index) {
        Widget? row;

        var element = widget.model[index];
        var value = widget.data[element.key]?.toString();

        switch (element.valueType) {
          case FormItemType.input:
            row = FixTitleWidthInput(
                titleWidth: 90.w,
                title: element.title,
                controller: TextEditingController(text: value?.toString()),
                onChanged: (value) {
                  widget.data[element.key] = value;
                });

            break;
          case FormItemType.selectPicker:
            row = BrnTextSelectFormItem(
              title: element.title,
              value: value,
              themeData: BrnFormItemConfig(
                  titleTextStyle: BrnTextStyle.withStyle(TextStyles.f14),
                  contentTextStyle: BrnTextStyle.withStyle(TextStyles.f14),
                  tipsTextStyle: BrnTextStyle.withStyle(TextStyles.f14)),
              onTap: () async {
                List<OptionModel>? options =
                    await element.request?.call(widget.data);
                var selected = await showPicker(options ?? []);
                setState(() {
                  widget.data[element.key] = selected.label;
                });
                element.formItemProps?.onSelectChange
                    ?.call(widget.data, selected);
              },
            );

            break;
          default:
            row = Gaps.empty;
            break;
        }
        return Offstage(
          offstage: element.formItemProps?.hidden == true,
          child: SizedBox(
            child: row,
          ),
        );
      },
      separatorBuilder: (context, index) => Gaps.empty,
      itemCount: widget.model.length,
    ));
  }

  bool validate() {
    var isValidate = true;
    for (var element in widget.model) {
      if (element.formItemProps?.required == true &&
          widget.data[element.key] == null) {
        showError(sprintf(ResKey.fieldRequiredSentence.tr, [element.title]));
        isValidate = false;
        break;
      }
    }
    return isValidate;
  }

  Map save() {
    return widget.data;
  }

  Future<OptionModel> showPicker(List<OptionModel> options, {dynamic value}) {
    Completer<OptionModel> completer = Completer<OptionModel>();

    var labels = options.map<String>((e) => e.label).toList();
    int selectedIndex = options.indexWhere((element) => element.value == value);
    selectedIndex == -1 ? 0 : selectedIndex;

    BrnMultiDataPicker(
      context: context,
      delegate: Brn1RowDelegate(labels, firstSelectedIndex: selectedIndex),
      confirmClick: (selectedIndexList) {
        var selectedOption = options[selectedIndexList[0]];
        completer.complete(selectedOption);
      },
    ).show();
    return completer.future;
  }
}
